package com.neusoft.hifly.netty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.netty.config.NettyConfig;
import com.neusoft.hifly.netty.socket.SocketServer;
import com.neusoft.hifly.netty.websocket.WebSocketServer;

/**
 * Title: Netty服务
 * <p>
 * Description: Netty启动类
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 辽宁畅通数据通信有限公司
 * 
 * @author
 * @version 1.0.0
 */
@Component
public class NettyRunner implements ApplicationRunner {

	@Autowired(required = false)
	private NettyConfig nettyConfig;

	@Autowired(required = false)
	private KafkaTemplate<String, Object> kafkaTemplate;

	@Override
	public void run(final ApplicationArguments args) {
		// 是否启动Socket服务
		if (nettyConfig.isSocketEnabled()) {
			// 两个一起启动，必须使用线程池
			if (nettyConfig.isWebSocketEnabled()) {
				new Thread(() -> {
					startSocket();
				}).start();
			} else {
				startSocket();
			}
		}

		// 是否启动Websocket服务
		if (nettyConfig.isWebSocketEnabled()) {
			// 两个一起启动，必须使用线程池
			if (nettyConfig.isSocketEnabled()) {
				new Thread(() -> {
					startWebSocket();
				}).start();
			} else {
				startWebSocket();
			}
		}
	}

	/**
	 * 启动Socket服务
	 */
	private void startSocket() {
		try {
			new SocketServer().start(nettyConfig, kafkaTemplate);
		} catch (Exception e) {
			Log.error(e.getMessage());
		}
	}

	/**
	 * 启动WebSocket服务
	 */
	private void startWebSocket() {
		try {
			new WebSocketServer().start(nettyConfig, kafkaTemplate);
		} catch (Exception e) {
			Log.error(e.getMessage());
		}
	}

}
